#include "net_work_task.h"
#include "include/socket.h"
#include "include/platform_windows_socket.h"
#include "NetTest.h"
using namespace SocketPool;

bool NetWorkTask::on_open(Socket* sc)
{
	char public_key[10] = {0};
	sc->read(public_key, 10);
	char valid_code[16];
	for (int i = 0; i < 8; ++i)
	{
		valid_code[i + 8] = valid_code[i] ^ public_key[6 + i%4];
	}
	sc->write("82", 2);
	sc->write(valid_code, 16);
	NetTest::instance()->set_socket(sc);
	return true;
}

void NetWorkTask::run()
{
	ClientSocket* sc = new ClientSocket();
	sc->initilize();
	if (sc->conncet("192.168.0.73", 8081))
	{
		if (on_open(sc))
		{
			do 
			{
				int len = 0;
				sc->read((char*)&len, 2);
				if (len > 2)
				{
					buff_.resize(read_pos_ + len);
					*(u_short*)&buff_[read_pos_] = len;
					sc->read(&buff_[read_pos_ + 2], len - 2);
					read_pos_ += len;
				}
				else
				{
					break;
				}

			} while (true);
			
			on_close(sc);
		}
	}
}

void NetWorkTask::on_read( Socket* sc )
{
	
}

void NetWorkTask::on_close( Socket* s )
{
	//s->disconnect();
	delete s;
	s = NULL;
}

NetWorkTask::NetWorkTask() : read_pos_(0)
{

}
